package com.oa.lms.apps.actions.absence;

import java.awt.Font;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.TextAnchor;

import com.oa.lms.apps.actions.BasicAction;
import com.oa.lms.apps.business.absence.IAbsenceCategoryService;
import com.oa.lms.apps.business.absence.IAbsenceOrderService;
import com.oa.lms.apps.business.absence.IReplyOrderService;
import com.oa.lms.apps.business.user.IUserInfoService;
import com.oa.lms.apps.business.user.IUsersService;
import com.oa.lms.apps.constants.IDEDStatus;
import com.oa.lms.apps.constants.IOrderStatus;
import com.oa.lms.apps.entity.absence.AbsenceCategoryValue;
import com.oa.lms.apps.entity.absence.AbsenceOrderValue;
import com.oa.lms.apps.entity.absence.ReplyOrderValue;
import com.oa.lms.apps.entity.user.UsersValue;

@SuppressWarnings("serial")
public class AbsenceOrderAction extends BasicAction {

	private IUsersService usersService;
	private IAbsenceCategoryService absenceCategoryService;
	private IAbsenceOrderService absenceOrderService;
	private IUserInfoService userInfoService;
	private AbsenceOrderValue orderInfo;
	private UsersValue usersInfo;
	private IReplyOrderService replyOrderService;

	private List<AbsenceOrderValue> absenceOrderList;
	private List<AbsenceCategoryValue> absenceCategoryList;
	private List<ReplyOrderValue> replyOrderList;

	private String categoryId;
	private String title;
	private String reason;
	private String startTime;
	private String endTime;
	private String totalHours;
	private String userId;
	private String createTime;
	private String orderId;
	private UsersValue userInfo;
	
	private String imageUrl;
	private String year;
	private String month;

	public String addAbsenceOrder() throws ParseException {
		UsersValue userInfo = (UsersValue) session.get("login_userInfo");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startTime_Date = sdf.parse(startTime);
		Date endTime_Date = sdf.parse(endTime);
		absenceOrderService.add(title, reason, startTime_Date, endTime_Date,
				Integer.parseInt(totalHours), Integer.parseInt(categoryId),
				userInfo.getUserId());
		return SUCCESS;
	}

	public String toAdd() {
		absenceCategoryList = absenceCategoryService.queryAbsenceCategory(null,
				IDEDStatus.ENABLE);
		return SUCCESS;
	}

	public String updateAbsenceOrder() throws ParseException {
		userInfo = (UsersValue) session.get("login_userInfo");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startTime_Date = sdf.parse(startTime);
		Date endTime_Date = sdf.parse(endTime);
		System.out.println(categoryId);
		absenceOrderService.modify(Integer.parseInt(orderId), title, reason,
				startTime_Date, endTime_Date, Integer.parseInt(totalHours),
				Integer.parseInt(categoryId), userInfo.getUserId());
		return SUCCESS;
	}

	public String toUpdate() {
		orderInfo = absenceOrderService.queryByOrderId(Integer
				.parseInt(orderId));
		absenceCategoryList = absenceCategoryService.queryAbsenceCategory(null,
				IDEDStatus.ENABLE);
		categoryId = orderInfo.getAbsenceCategory().getCategoryId().toString();
		userId = orderInfo.getUserItem().getUserId().toString();
		return SUCCESS;
	}

	public String toCancel() throws ParseException{
		String orderInfo = absenceOrderService.cancelAbsenceOrder(Integer.parseInt(orderId));
		String[] orderInfoArray = orderInfo.split(",");
		String userNameInOrder = orderInfoArray[0];
		String titleInOrder = orderInfoArray[1];
		replyOrderService.replyOrderCancelNotice(Integer.parseInt(orderId), userNameInOrder, titleInOrder);
		return SUCCESS;
	}
	
	
	public String toQueryForCheck() {
		userInfo = (UsersValue) session.get("login_userInfo");
		totalpage = absenceOrderService.getTotalPageNumber(null, null,userInfo.getUserInfo().getPostInfo().getPostId(), rows);
		absenceOrderList = absenceOrderService.queryAbsenceOrder(null, null,
				userInfo.getUserInfo().getPostInfo().getPostId(), rows,
				currpage);
		return SUCCESS;
	}
	
	public String queryForCheckNum() throws Exception {
		String number = "";
		userInfo = (UsersValue) session.get("login_userInfo");
		absenceOrderList = absenceOrderService.queryAbsenceOrder(null, null, userInfo.getUserInfo().getPostInfo().getPostId(), 100, 1);
		if(absenceOrderList.size() != 0 && absenceOrderList != null){
			number = Integer.toString(absenceOrderList.size());
		}else{
			number = "0";
		}
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().write(number);
		return null;
	}

	public String toQuery() {
		userInfo = (UsersValue) session.get("login_userInfo");
		totalpage =absenceOrderService.getTotalPageNumber(null, null, IOrderStatus.PASS, rows);
		absenceOrderList = absenceOrderService.queryAbsenceOrder(null, null, IOrderStatus.PASS, rows, currpage);
		return SUCCESS;
	}

	public String toShowOrderDetail() {
		orderInfo = absenceOrderService.queryByOrderId(Integer
				.parseInt(orderId));
		replyOrderList = replyOrderService.queryReplyOrder(orderInfo
				.getOrderId());
		return SUCCESS;
	}

	public String toShowOrderSelfDetail() {
		orderInfo = absenceOrderService.queryByOrderId(Integer.parseInt(orderId));
		replyOrderList = replyOrderService.queryReplyOrder(orderInfo.getOrderId());
		return SUCCESS;
	}

	public String toListOrderSelf() {
		userInfo = (UsersValue) session.get("login_userInfo");
		totalpage =absenceOrderService.getTotalPageNumber(null, userInfo.getUserId(), null, rows);
		absenceOrderList = absenceOrderService.queryAbsenceOrder(null,userInfo.getUserId(), null, rows, currpage);

		return SUCCESS;
	}
	
	public String toSubmitAbsenceOrder(){
		absenceOrderService.nextCheck(Integer.parseInt(orderId));
		return SUCCESS;
	}
	
	public String toQueryOrderByDate(){
		return SUCCESS;
	}
	
	public String toQueryOrderByMonth(){
		return SUCCESS;
	}
	
	public String queryOrderByDate() throws Exception{
		UsersValue userInfo = (UsersValue) session.get("login_userInfo");
		absenceCategoryList = absenceCategoryService.queryAbsenceCategory(null, IDEDStatus.ENABLE);
		DefaultPieDataset dataset = new DefaultPieDataset();
		
		for (AbsenceCategoryValue  absenceCategory: absenceCategoryList){
			dataset.setValue(absenceCategory.getCategoryName(), absenceOrderService.queryAbsenceOrderByDate(absenceCategory.getCategoryId(), userInfo.getUserId(), startTime, endTime));
		}
		
		JFreeChart chart1 = ChartFactory.createPieChart3D("日期区间请假统计饼状图(单位：小时)", dataset, true, false, false);

		PiePlot3D plot1 = (PiePlot3D) chart1.getPlot();
		// 图片中显示百分比:默认方式
		plot1.setLabelGenerator(new StandardPieSectionLabelGenerator(
				StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
		// 图片中显示百分比:自定义方式，{0} 表示选项， {1} 表示数值，
		//{2} 表示所占比例 ,小数点后两位
		plot1.setLabelGenerator(new StandardPieSectionLabelGenerator(
				"{0}={1}({2})", NumberFormat.getNumberInstance(),
				new DecimalFormat("0.00%")));
		// 图例显示百分比:自定义方式， {0} 表示选项， {1} 表示数值， {2} 表示所占比例
		plot1.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
						"{0}"));
		// 指定图片的透明度(0.0-1.0)
		plot1.setForegroundAlpha(1.0f);
		// 指定显示的饼图上圆形(true)还椭圆形(false)
		plot1.setCircular(true);
		// 设置图上分类标签label的字体，解决中文乱码
		plot1.setLabelFont(new Font("黑体", Font.PLAIN, 12));
		// 设置图上分类标签label的最大宽度，相对与plot的百分比
		plot1.setMaximumLabelWidth(0.2);
		// 设置3D饼图的Z轴高度（0.0～1.0）
		plot1.setDepthFactor(0.07);
		//设置起始角度，默认值为90，当为0时，起始值在3点钟方向
		plot1.setStartAngle(45);
 
		// 设置图标题的字体，解决中文乱码
		TextTitle textTitle = chart1.getTitle();
		textTitle.setFont(new Font("黑体", Font.PLAIN, 20));

		// 设置Legend部分字体，解决中文乱码
		chart1.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
		
		ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
		String filename = ServletUtilities.saveChartAsPNG(chart1, 800, 450, info, httpSession);
		imageUrl = request.getContextPath()+"/servlet/DisplayChart?filename="+filename;
		return SUCCESS;
	}
	
	public String queryOrderByMonth() throws Exception{
		UsersValue userInfo = (UsersValue) session.get("login_userInfo");
		absenceCategoryList = absenceCategoryService.queryAbsenceCategory(null, IDEDStatus.ENABLE);
		String searchMonth = year + month;
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		
		for(AbsenceCategoryValue  absenceCategory: absenceCategoryList){
			dataset.addValue(absenceOrderService.queryAbsenceOrderByMonth(absenceCategory.getCategoryId(), userInfo.getUserId(), searchMonth), "请假类型", absenceCategory.getCategoryName());
		}
		
		JFreeChart chart = ChartFactory.createBarChart3D(year+"年"+month+"月份请假统计柱状图", "请假类型", "请假时间（单位：小时）", dataset, PlotOrientation.VERTICAL, true, false, false);
		
		CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象
		BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer();
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());//显示每个柱的数值 
		renderer.setBaseItemLabelsVisible(true); 
		//注意：此句很关键，若无此句，那数字的显示会被覆盖，给人数字没有显示出来的问题 
		renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition( 
		ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); 
		renderer.setItemLabelAnchorOffset(2D);// 设置柱形图上的文字偏离值 

		plot.setRenderer(renderer);

		CategoryAxis domainAxis=plot.getDomainAxis();
		//水平底部列表
		domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14));
		//水平底部标题
		domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12));
		//垂直标题
	    ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状
	    rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));

	    chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
	    chart.getTitle().setFont(new Font("黑体", Font.BOLD, 20));
		
		ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
		String filename = ServletUtilities.saveChartAsPNG(chart, 1000, 370, info, httpSession);
		imageUrl = request.getContextPath()+"/servlet/DisplayChart?filename="+filename;
		return SUCCESS;
	}
	
	// Getter and Setter

	public IUserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(IUserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public IUsersService getUsersService() {
		return usersService;
	}

	public void setUsersService(IUsersService usersService) {
		this.usersService = usersService;
	}

	public IAbsenceCategoryService getAbsenceCategoryService() {
		return absenceCategoryService;
	}

	public void setAbsenceCategoryService(
			IAbsenceCategoryService absenceCategoryService) {
		this.absenceCategoryService = absenceCategoryService;
	}

	public IAbsenceOrderService getAbsenceOrderService() {
		return absenceOrderService;
	}

	public void setAbsenceOrderService(IAbsenceOrderService absenceOrderService) {
		this.absenceOrderService = absenceOrderService;
	}

	public List<AbsenceCategoryValue> getAbsenceCategoryList() {
		return absenceCategoryList;
	}

	public void setAbsenceCategoryList(
			List<AbsenceCategoryValue> absenceCategoryList) {
		this.absenceCategoryList = absenceCategoryList;
	}

	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getReason() {
		return reason;
	}

	public void setReason(String reason) {
		this.reason = reason;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getTotalHours() {
		return totalHours;
	}

	public void setTotalHours(String totalHours) {
		this.totalHours = totalHours;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getCreateTime() {
		return createTime;
	}

	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public AbsenceOrderValue getOrderInfo() {
		return orderInfo;
	}

	public void setOrderInfo(AbsenceOrderValue orderInfo) {
		this.orderInfo = orderInfo;
	}

	public List<AbsenceOrderValue> getAbsenceOrderList() {
		return absenceOrderList;
	}

	public void setAbsenceOrderList(List<AbsenceOrderValue> absenceOrderList) {
		this.absenceOrderList = absenceOrderList;
	}

	public UsersValue getUsersInfo() {
		return usersInfo;
	}

	public void setUsersInfo(UsersValue usersInfo) {
		this.usersInfo = usersInfo;
	}

	public UsersValue getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UsersValue userInfo) {
		this.userInfo = userInfo;
	}

	public List<ReplyOrderValue> getReplyOrderList() {
		return replyOrderList;
	}

	public void setReplyOrderList(List<ReplyOrderValue> replyOrderList) {
		this.replyOrderList = replyOrderList;
	}

	public IReplyOrderService getReplyOrderService() {
		return replyOrderService;
	}

	public void setReplyOrderService(IReplyOrderService replyOrderService) {
		this.replyOrderService = replyOrderService;
	}

	public String getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}
	

}
